package com.decodeUtil;

import android.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 项目名称：yzf_android_test
 * 类描述：日志加密解密工具
 * 创建人：罗浩
 * 创建时间：2020/4/29 16:02
 * 修改人：Administrator
 * 修改时间：2020/4/29 16:02
 * 修改备注：
 */
public class DesUtil {
    // 密钥 长度不得小于24
    private static final String secretKey = "LdgOQEGIXyU56scp9u5kr3I1";
    // 向量 可有可无 终端后台也要约定
    private static final String iv = "88323502";
    // 加解密统一使用的编码方式
    private static final String encoding = "gbk";

    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @return
     * @throws Exception
     */
    public static String encode(String plainText) throws Exception {
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        Key deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        // 执行加密操作
        byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
        String bTemp = Base64.encodeToString(encryptData, Base64.DEFAULT);
        //返回前处理掉自动添加的\n换行字段
        return bTemp.replaceAll("[\\s*\t\n\r]", "");
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText) throws Exception {
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        Key deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        //解密操作
        byte[] decryptData = cipher.doFinal(Base64.decode(encryptText, Base64.DEFAULT));
        return new String(decryptData, encoding);
    }
}

